'use strict';

const Controller = require('egg').Controller;

class ListController extends Controller {
    //创建
    async create() {
        let {ctx,service} = this;
        //1.获取前端传递的参数
        let author = 'lixd',  //作者
            num = 0;  //阅读数
        let {title,create_time,status,import_num} = ctx.request.body;
        //2.容错处理
        if(title && create_time && status && import_num){
            try{
                await service.home.put(title,create_time,status,import_num,author,num);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //更新
    async update(){
        let {ctx,service} = this;
        //1.获取前端传递的参数
        let {title,create_time,status,import_num} = ctx.request.body;
        let {id} = ctx.params;
        //2.容错处理
        if(title && create_time && status && import_num){
            try{
                await service.home.update(title,create_time,status,import_num,id);
                ctx.body = {
                    code:1,
                    msg:'修改成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //删除
    async destroy(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        if(id){
            try{
                await service.home.del(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //查询
    async index(){
        let {ctx,service} = this;
        //start 起始下标  count 每页的条数
        let {start=0,count=2} = ctx.query;
        let list = await service.home.booklist(start,count);
        //查总条数
        let total = await service.home.total();
        console.log("total",total);
        ctx.body = {
            code:1,
            data:list,
            total:total[0]['count(*)']
        }
    }
}

module.exports = ListController;
